import { reactive, computed, toRefs } from "vue";
import { gantt } from "dhtmlx-gantt";

/**
 * @description 甘特图公共方法组件
 * */
export const useGantt = () => {
  const state: any = reactive({
    tasks: {}, // 任务对象
    columns: [], // 显示列设置
    scaleTime: "day", // 显示单位 minute, hour, day, week, quarter, month, year
    dateScale: "%Y-%m-%d", // 时间显示格式
    showSearch: true, // 是否显示搜索栏
    unitTime: "", // 切换日月周季
    options: [
      {
        label: "日",
        value: "day",
      },
      {
        label: "周",
        value: "week",
      },
      {
        label: "月",
        value: "month",
      },
      {
        label: "季度",
        value: "year",
      },
    ],
    searchParam: {
      dayType: "",
      isCollapse: false,
      hideGrid: false,
      workbenchType: "",
    },
    searchColumns: [
      {
        type: "switch",
        label: "折叠",
        fieldName: "isCollapse",
        initValue: false,
        placeholder: "",
        disabled: false, // 是否禁用
        loading: false, // 是否显示loading
        activeValue: true, // 打开时的值
        inactiveValue: false, // 关闭时的值
        activeColor: "#3171F1", // 打开时的颜色
        inactiveColor: "#C0CCDA", // 关闭时的颜色
        borderColor: "", // 开关边框颜色
        validateEvent: true, // 切换时是否触发表单校验
        change: (val: any) => {
          changeCollapse(val);
        },
      },
      {
        type: "switch",
        label: "隐藏表头",
        fieldName: "hideGrid",
        initValue: false,
        placeholder: "",
        disabled: false, // 是否禁用
        loading: false, // 是否显示loading
        activeValue: true, // 打开时的值
        inactiveValue: false, // 关闭时的值
        activeColor: "#3171F1", // 打开时的颜色
        inactiveColor: "#C0CCDA", // 关闭时的颜色
        borderColor: "", // 开关边框颜色
        validateEvent: true, // 切换时是否触发表单校验
        change: (val: any) => {
          toggleGrid();
        },
      },
      {
        type: "switch",
        label: "隐藏进度",
        fieldName: "hideChart",
        initValue: false,
        placeholder: "",
        disabled: false, // 是否禁用
        loading: false, // 是否显示loading
        activeValue: true, // 打开时的值
        inactiveValue: false, // 关闭时的值
        activeColor: "#3171F1", // 打开时的颜色
        inactiveColor: "#C0CCDA", // 关闭时的颜色
        borderColor: "", // 开关边框颜色
        validateEvent: true, // 切换时是否触发表单校验
        change: (val: any) => {
          toggleChart();
        },
      },
    ],
    initGanttConfig: {
      show_today: true,
      show_errors: false,
      show_empty_state: true, // 默认展示空图片
      grid_elastic_columns: true, // 列将通过收缩或拉伸来适合表的宽度
      show_loading: true, //增加加载中状态
      xml_date: "%Y-%m-%d", // 时间默认配置
      auto_types: true, // 将包含子任务的任务转换为项目，将没有子任务的项目转换回任务
      readonly: false, // 设置为可编辑
      // autosize: true, // 自适应尺寸  y轴自适应（不滚动）  x    xy
      autofit: false, // 表格列宽自适应
      autoscroll: false, // 把任务或者连线拖拽到浏览器屏幕外时，自动触发滚动效果
      show_links: true, // 是否显示依赖连接线
      drag_progress: true, //取消任务进度条进度拖动
      show_progress: true, // 是否显示进度按钮
      show_chart: true, // 是否展示右侧图表
      details_on_create: true, // 通过单击+按钮在创建新事件时打开灯箱
      resize_rows: false, // 启用通过拖放调整行高的能力
      resize_columns: true, // 启用通过拖放调整行高的能力
      order_branch: true, // 允许拖动排序
      order_branch_free: true, // 激活分支模式，允许在整个gant中重新排序任务
      show_quick_info: false, // 显示快速提示弹窗
      work_time: true, // 默认工作时间
      scale_height: 60, // 表头行高
      row_height: 38, // 内容row高度
    },
    initGanttTemplates: {
      // project文件图标为空
      grid_folder: (item: any) => {
        return "";
      },
      // task文件图标为空
      grid_file: (item: any) => {
        return "";
      },
      // 周末红色标注
      timeline_cell_class: (task: any, date: Date) => {
        if (!gantt.isWorkTime(date)) return "week_end";
        return "";
      },
    },
  });

  function toggleGrid() {
    gantt.config.show_grid = !gantt.config.show_grid;
    gantt.render();
  }

  function toggleChart() {
    gantt.config.show_chart = !gantt.config.show_chart;
    gantt.render();
  }

  function changeCollapse(val: any) {
    if (val) {
      collapseAll();
    } else {
      expandAll();
    }
  }

  function collapseAll() {
    gantt.batchUpdate(function () {
      gantt.eachTask(function (task) {
        gantt.close(task.id);
      });
    });
  }

  function expandAll() {
    gantt.batchUpdate(function () {
      gantt.eachTask(function (task) {
        gantt.open(task.id);
      });
    });
  }

  function setTimelineCellContent() {
    gantt.templates.timeline_cell_content = function (task, date) {
      if (task.customData && task.customData[+date]) {
        return `<div class="custom_comment" data-task-id="${task.id}">${
          task.customData[+date]
        }</div>`;
      }
      return "";
    };
  }
  const radioSwitchChange = (e: string) => {
    switch (e) {
      case "day":
        switchToDay();
        break;
      case "week":
        switchToWeek();
        break;
      case "month":
        switchToMonth();
        break;
      case "year":
        switchToQuarter();
        break;
      default:
        break;
    }
  };

  //日 周 月 季度 切换
  const switchToDay = () => {
    gantt.config.xml_date = "%Y-%m-%d";
    gantt.config.scale_unit = "month";
    gantt.config.step = 1;
    gantt.config.date_scale = "%Y年%M";
    gantt.config.subscales = [
      {
        unit: "day",
        step: 1,
        date: "%d日 周%D",
      },
    ];
    gantt.render();
  };
  const switchToWeek = () => {
    gantt.config.scale_unit = "week";
    gantt.config.step = 1;
    gantt.config.date_scale = "%Y年%M";
    gantt.templates.date_scale = null;
    gantt.config.subscales = [
      {
        unit: "week",
        step: 1,
        date: "第%W周",
      },
      // {
      //   unit: "day",
      //   step: 1,
      //   date: "%d日",
      // },
    ];
    gantt.render();
  };
  const switchToMonth = () => {
    gantt.config.scale_unit = "month";
    gantt.config.step = 1;
    gantt.config.date_scale = "%Y年";
    gantt.templates.date_scale = null;
    gantt.config.subscales = [
      {
        unit: "month",
        step: 1,
        date: "%M",
      },
    ];
    gantt.render();
  };
  const switchToQuarter = () => {
    gantt.config.scale_unit = "year";
    gantt.config.step = 1;
    gantt.config.date_scale = "%Y年";
    gantt.config.subscales = [
      {
        unit: "month",
        step: 1,
        date: "%M",
      },
      {
        unit: "week",
        step: 1,
        date: "第%W周",
      },
      // {
      //   unit: "quarter",
      //   step: 1,
      //   format: function (date: any) {
      //     const dateToStr = gantt.date.date_to_str("%M");
      //     const endDate = gantt.date.add(
      //       gantt.date.add(date, 3, "month"),
      //       -1,
      //       "day"
      //     );
      //     return dateToStr(date) + " - " + dateToStr(endDate);
      //   },
      // },
    ];
    gantt.render();
  };

  // 下载
  function exportData(raw) {
    const previousWidth = gantt.config.grid_width;
    gantt.config.grid_width = 0;
    gantt.config.columns.forEach(function (column, index) {
      const nodes = document.querySelectorAll(
        `.gantt_cell[data-column-index="${index}"]`
      );
      let maxWidth = 0;
      nodes.forEach(function (node) {
        if (maxWidth < node.scrollWidth) {
          maxWidth = node.scrollWidth;
        }
      });
      gantt.config.grid_width += maxWidth;
      column.previous_width = column.width;
      column.width = maxWidth + 12; // 12px is the padding-left + padding right
    });

    gantt.exportToPDF({
      raw: raw,
    });

    gantt.config.grid_width = previousWidth;
    gantt.config.columns.forEach(function (column, index) {
      column.width = column.previous_width;
      delete column.previous_width;
    });

    if (raw) {
      gantt.render();
    }
  }
  function initEmptyState() {
    gantt.ext.emptyStateElement.renderContent = function (container) {
      const placeholderTextElement = `<div class='gantt_empty_state_text'>
      <div class='gantt_empty_state_text_description'>
         暂无任务</div>
      </div>`;
      const placeholderImageElement =
        "<div class='gantt_empty_state_image'></div>";

      const placeholderContainer = `<div class='gantt_empty_state'>
         ${placeholderImageElement}${placeholderTextElement}</div>`;
      container.innerHTML = placeholderContainer;
    };
  }
  function initGanttFunction() {
    // gantt.config.show_chart = false;
    // console.log("gantt.config", gantt);
    gantt.clearAll(); // 清空之前的配置
    gantt.i18n.setLocale("cn"); // 设置中文
    // 跳过周末
    gantt.ignore_time = function (date) {
      return date.getDay() == 0 || date.getDay() == 6;
    };
    // 默认config配置
    gantt.config = {
      ...gantt.config,
      ...state.initGanttConfig,
    };
    // 默认templates配置
    gantt.templates = {
      ...gantt.templates,
      ...state.initGanttTemplates,
    };

    gantt.$zoomToFit = true;

    // gantt引用插件api
    gantt.plugins({
      export_api: true,
      quick_info: false,
      tooltip: true,
      critical_path: true,
      fullscreen: true,
      marker: true,
    });
  }

  function layoutCommon() {
    // 自定义布局，可在组件内部定义
    gantt.config.layout = {
      cols: [
        {
          width: 400,
          min_width: 200,
          rows: [
            {
              view: "grid",
              scrollX: "gridScroll",
              scrollable: true,
              scrollY: "scrollVer",
            },
            { view: "scrollbar", id: "gridScroll", group: "horizontal" },
          ],
        },
        { resizer: true, width: 1 },
        {
          rows: [
            { view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer" },
            { view: "scrollbar", id: "scrollHor", group: "horizontal" },
          ],
        },
        { view: "scrollbar", id: "scrollVer" },
      ],
    };
  }
  return {
    ...toRefs(state),
    changeCollapse,
    radioSwitchChange,
    exportData,
    initGanttFunction,
    initEmptyState,
    layoutCommon,
    gantt,
  };
};
